import React, { useState, useEffect, useCallback, useRef, forwardRef } from 'react';
import { Select, Input, Space, Button } from 'antd';
import styles from '../index.less';
import { getMessage, TextWidget } from '@inbiz/react';
import { connect, mapProps } from '@formily/react';

const Option = Select.Option;

interface IProps {
  options: Array<number>; // 分页可选择数量数组
  total: number; // 记录总数
  current: number; // 当前页码
  pageSize?: number; // 默认分页的单页记录数量
  size?: 'large' | 'middle' | 'small'; // 控件大小
  onChange?: Function;
  refs?: any;
  pageSizeview?: string;
  nextPage?: string;
  previousPage?: string;
}

const Pagination = forwardRef((props: IProps, ref: any) => {
  // 记录总数
  const [total, $total] = useState<number>(0);
  // 当前页码
  const [current, $current] = useState<number>(1);
  // 分页量
  const [pageSize, $pageSize] = useState<number>(5);
  // 总页数
  const [pageCount, $pageCount] = useState(0);
  // 分段值
  const [section, $section] = useState('');
  // 跳页当前页
  const [jumpCurrent, $jumpCurrent] = useState<number | string>(1);

  // 输入框对象
  const iptObj = useRef<any>();

  // 内部触发onChange许可
  const shouldChange = useRef<boolean>();

  // 同步更新记录总数
  useEffect(() => {
    $total(props.total);
  }, [props.total]);

  // 同步更新当前页码
  useEffect(() => {
    $current(props.current);
    $jumpCurrent(props.current);
  }, [props.current]);

  // 同步更新pageSize
  useEffect(() => {
    props.pageSize && $pageSize(props.pageSize);
  }, [props.pageSize]);

  // 改变触发onChange
  useEffect(() => {
    if (shouldChange.current) {
      props.onChange &&
        props.onChange({
          current,
          pageSize,
        });
      shouldChange.current = false;
    }
  }, [current, pageSize]);

  // 计算当前段及总页数
  useEffect(() => {
    const pageCount = Math.ceil(total / pageSize);
    $pageCount(pageCount);
    let now = current;
    if (pageCount && now > pageCount) {
      now = pageCount;
      $current(now);
      $jumpCurrent(now);
      shouldChange.current = true;
      return;
    }
    let section = '' + (pageSize * (current - 1) + 1);
    if (pageSize * (current - 1) + 1 < total) {
      if (pageSize * current > total) {
        section += '-' + total;
      } else {
        section += '-' + pageSize * current;
      }
    }
    $section(section);
  }, [total, current, pageSize]);

  // 跳页页码变化
  const iptChange = useCallback(
    (e: { target: HTMLInputElement }) => {
      if (e.target.value === '') {
        $jumpCurrent('');
        return;
      }
      let value = parseInt(e.target.value);
      if (value && value > 0 && value <= pageCount) {
        if (value > 0 && value <= pageCount) {
          $jumpCurrent(value);
        }
      }
    },
    [pageCount],
  );

  // 跳页
  const jumpPage = useCallback(
    (e) => {
      e.stopPropagation();
      e.preventDefault();
      let iptv = e.target as HTMLInputElement;
      let value = parseInt(iptv.value);
      if (value && value > 0) {
        if (value <= pageCount) {
          $current(Number(value));
        } else {
          $current(pageCount);
          $jumpCurrent(pageCount);
        }
        shouldChange.current = true;
      } else {
        return;
      }
      iptObj.current?.blur();
      props.refs?.current?.focus();
    },
    [pageCount],
  );

  return (
    <>
      {total && pageCount > 1 ? (
        <div className={styles['inbiz-eform-dynamic-list-pagination-box']}>
          <div className={styles['left-content']}>
            <Select
              style={{ width: 100 }}
              size={props.size || 'small'}
              value={pageSize}
              placement="bottomLeft"
              getPopupContainer={(triggerNode) => triggerNode.parentElement}
              onChange={(e: number) => {
                const pageCount = Math.ceil(total / e);
                if (pageCount && current <= pageCount) {
                  shouldChange.current = true;
                }
                $pageSize(e);
              }}
            >
              {Array.isArray(props.options) &&
                props.options.map((item) => {
                  return (
                    <Option value={item} key={item} title={` ${item} ${props.pageSizeview}`}>
                      {item} {props.pageSizeview}
                    </Option>
                  );
                })}
            </Select>
          </div>
          <div className={styles['right-content']}>
            <Space>
              {/* <span className={styles['section-text']}>
                {section} / {total}
              </span> */}
              <Button
                size={props.size || 'small'}
                disabled={current === 1}
                onClick={() => {
                  $current(current - 1);
                  $jumpCurrent(current - 1);
                  shouldChange.current = true;
                }}
                title={props.previousPage}
              >
                {/* <TextWidget>EformDynamicList.previousPage</TextWidget> */}
                &lt;
              </Button>
              <Button
                size={props.size || 'small'}
                disabled={current === pageCount}
                onClick={() => {
                  $current(current + 1);
                  $jumpCurrent(current + 1);
                  shouldChange.current = true;
                }}
                title={props.nextPage}
              >
                {/* <TextWidget>EformDynamicList.nextPage</TextWidget> */}
                &gt;
              </Button>
              <Input
                style={{ width: 45, textAlign: 'center' }}
                size={props.size || 'small'}
                ref={iptObj}
                value={jumpCurrent}
                onChange={iptChange}
                onPressEnter={jumpPage}
              />
              <span className={styles['pagecount-text']}>/ {pageCount} </span>
            </Space>
          </div>
        </div>
      ) : null}
    </>
  );
});

// export default Pagination;

export default connect(
  Pagination,
  mapProps({}, (props: any, field: any) => {
    const { ...others } = props;
    others.pageSizeview = getMessage('EformDynamicList.pageSizeview');
    others.nextPage = getMessage('EformDynamicList.nextPage');
    others.previousPage = getMessage('EformDynamicList.previousPage');
    return { ...others };
  }),
);
